package application.common.cron4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.cron4j.ITask;

import application.common.model.Board;
import application.common.render.HttpClientResult;
import application.common.util.HttpUtil;
import application.common.util.ShiroUtil;
import net.sf.json.JSONObject;

public class BoardTask implements ITask{
	private final Log log = Log.getLog(getClass());
	private boolean isEnd=true;
	public void run() {
		if(isEnd) {
			isEnd=false;
			if(ShiroUtil.getConfig()!=null && !StrKit.isBlank(ShiroUtil.getConfig().getSynURL())) {
				try {
					List<Board> boards=Board.dao.findAll();
					if(boards!=null && boards.size()>0) {
						Map<String, String> params =new HashMap<String,String>();
						params.put("rows", JsonKit.toJson(boards));
						params.put("cabinetId", ShiroUtil.getAuth());
						HttpClientResult httpClientResult=HttpUtil.doPost(String.format("%s/api/cab/saveBoards", ShiroUtil.getConfig().getSynURL()), params);
						if(httpClientResult==null) {
							isEnd=true;
							return;
						}
						if(httpClientResult.getCode()!=200) {
							isEnd=true;
							return;	
						}
						String content=httpClientResult.getContent();
						if(StrKit.isBlank(content)) {
							isEnd=true;
							return;	
						}
						JSONObject jsonObject=JSONObject.fromObject(content);
						if(jsonObject==null) {
							isEnd=true;
							return;	
						}
						if(jsonObject.has("code")) {
							int code=jsonObject.getInt("code");
							if(code!=200) {
								isEnd=true;
								return;	
							}
							log.info("日志同步成功");
							isEnd=true;
						}else {
							log.info("日志同步异常！");
							isEnd=true;
						}
					}else {
						log.info("暂无日志需要同步！");
						isEnd=true;
					}
				}catch (Exception e) {
					log.info("日志同步异常！",e);
					isEnd=true;
				}
			}
			isEnd=true;
		}
	}

	public void stop() {
	}

}
